<?php
/**
 * Created by PhpStorm.
 * User: zouyanan
 * Date: 2019/5/11
 * Time: 下午10:35
 */

namespace app\userapi\controller;
use app\common\controller\Api;
use think\Exception;
use fast\Random;
use think\Validate;
use app\common\library\Token;

class Login extends Api
{
    protected $noNeedLogin = ['checkphone','smsCode','register','login'];
    protected $noNeedRight = '*';


    //手机号验证
    public function checkphone(){
        header('Access-Control-Allow-Origin: *');
        header('Access-Control-Allow-Credentials: true');
        header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
        header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");
        ob_clean();
        $mobile = $this->request->request('mobile');
        $code = $this->request->request("code");
        $id = db('user')->where('mobile', $mobile)->value('id');
        if ($id) {
            $this->error('手机号已注册');
        }
        if ($mobile && !Validate::regex($mobile, "^1\d{10}$")) {
            $this->error('手机号格式不正确');
        }
        $checkCode = $this->checkCode($mobile, $code, 1);
        if (!$checkCode) {
            $this->error('验证码错误');
        }else{
            $this->success("验证码正确");
        }
    }





    public function register()
    {
        header('Access-Control-Allow-Origin: *');
        header('Access-Control-Allow-Credentials: true');
        header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
        header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");
        ob_clean();
        $mobile = $this->request->request('mobile');
        $password = $this->request->request('password');
        $nickname = $this->request->request("nickname");
        if(!$mobile || !$password){
            $this->error("缺少参数");
        }
        $id = db('user')->where('mobile', $mobile)->value('id');
        if ($id) {
            $this->error('手机号已注册');
        }
        $salt = Random::alnum();
        $res = db('user')->insertGetId([
            'mobile'   => $mobile,
            'nickname' => $nickname,
            'password' => $this->auth->getEncryptPassword($password, $salt),
            'salt' => $salt,
            'type' => 2, //用户
            'createtime'=> time()
        ]);
        //db("user_renter")->insert(['User_id'=>$res]);
        if ($res) {
            $this->success('注册成功');
        } else {
            $this->error('注册失败');
        }
    }

    //用户登录
    public function login()
    {
        header('Access-Control-Allow-Origin: *');
        header('Access-Control-Allow-Credentials: true');
        header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
        header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");
        $user = db('user');
        $mobile = $this->request->request('mobile');
        $password = $this->request->request('password');
        if(!$mobile || !$password){
            $this->error('缺少参数');
        }
        $user_info = $user->field("id,password,salt")->where('mobile',$mobile)->where("type",2)->find();
        if(!$user_info){
            $this->error('未找到该用户');
        }
        if($user_info['password'] != $this->auth->getEncryptPassword($password,$user_info['salt'])){
            $this->error('密码错误');
        }
        $res = $this->auth->direct($user_info['id']);
        if ($res) {
            $userInfo = $this->auth->getUserinfo();
            $personal_info = db('user a')
               // ->join("user_renter b",'a.id = b.user_id','LEFT')
                ->field("a.nickname,a.mobile,a.idcard,a.avatar,a.gender")
                ->field("a.num_collect,a.num_attention,a.num_view")
                ->where('a.id',$userInfo['id'])
                ->find();
            $data = [
                'token'   => $userInfo['token'],
                'personal_info' => $personal_info
            ];
            $this->success('登录成功',$data);
        } else {
            $this->error('登录失败');
        }
    }


    /**
     * 短信验证码
     */
    public function smsCode()
    {
        header('Access-Control-Allow-Origin: *');
        //上面第一行说到的Access-Control-Allow-Origin有多种设置方法：
        //（1）设置*是最简单粗暴的，但是服务器出于安全考虑，肯定不会这么干，而且，如果是*的话，游览器将不会发送cookies，即使你的XHR设置了withCredentials
        //（2） 指定域，如上图中的http://172.20.0.206，一般的系统中间都有一个nginx，所以推荐这种,例如：'Access-Control-Allow-Origin:http://172.20.0.206'
        //（3）动态设置为请求域，多人协作时，多个前端对接一个后台，这样很方便
        //withCredentials：表示XHR是否接收cookies和发送cookies，也就是说如果该值是false，响应头的Set-Cookie，浏览器也不会理，并且即使有目标站点的cookies，浏览器也不会发送。

        header('Access-Control-Allow-Credentials: true'); //是否允许后续请求携带认证信息（cookies）,该值只能是true,否则不返回

        //预检请求（参考文章：http://www.php.cn/div-tutorial-378889.html） --- 一般不用设置
        //与简单请求不同的是，option请求多了2个字段：
        //Access-Control-Request-Method：该次请求的请求方式
        //Access-Control-Request-Headers：该次请求的自定义请求头字段
        //Access-Control-Max-Age 表明该响应的有效时间为 86400 秒，也就是 24 小时。在有效时间内，浏览器无须为同一请求再次发起预检请求。请注意，浏览器自身维护了一个最大有效时间，如果该首部字段的值超过了最大有效时间，将不会生效
        //预检结果缓存时间,也就是上面说到的缓存啦
        //'Access-Control-Max-Age: 86400'

        header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS'); //允许的请求类型

        header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept"); // 允许的请求头字段

        $mobile = $this->request->request('mobile');
        $type = $this->request->request('type'); //1注册,2登录,3修改密码
        if (!$mobile) {
            $this->error('请填写手机号');
        }
        if (!$type) {
            $this->error('参数错误');
        }
        $info = db('telcode')->where('ext', $type)->where('tel', $mobile)->find();
        if ($info && $info['expiretime'] > time()) {
            $code = $info['code'];
        } else {
            db('telcode')->where('ext', $type)->where('tel', $mobile)->delete();
            $code = mt_rand(100000,999999);
        }
        $sms = new \app\userapi\controller\Sms();
        $result = $sms->sms($mobile,$code);
        if($result == 200){
            $info = db('telcode')->where('ext', $type)->where('tel', $mobile)->find();
            if (!$info) {
                $res = db('telcode')->insertGetId(['tel' => $mobile, 'ext' => $type, 'code' => $code, 'expiretime' => time() + 180]);
            }
            $this->success("发送成功");
        }elseif($result == 100){
            $this->error("发送失败");
        }else{
            $this->error($result);
        }
    }



    /**
     * 核验验证码
     */
     protected function checkCode($mobile, $code, $type = 1){
         header('Access-Control-Allow-Origin: *');
         header('Access-Control-Allow-Credentials: true');
         header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
         header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");
        switch ($type) {
            case 1:
                $map['ext'] = 1;
                break;
            case 2:
                $map['ext'] = 2;
                break;
            case 3:
                $map['ext'] = 3;
				break;
            default:
                $map['ext'] = 1;
                break;
        }
        $map['tel'] = $mobile;
        $info = db('telcode')->field("*")->where($map)->find();
        if (!$info) {
            return 0;
		}
        if (($code != $info['code']) || ($info['expiretime'] <= time())) {
            db('telcode')->where('tel', $mobile)->delete();
            return 0;
        }
        db('telcode')->where('tel', $mobile)->delete();
        db('telcode')->where('expiretime', '<=', time())->delete();
       return 1;
    }

}